//
//  TopScrollView.swift
//  lookLikeIweekly
//
//  Created by ZhangXiaoqian on 16/6/5.
//  Copyright © 2016年 Mainzxq. All rights reserved.
//

import UIKit

protocol MyScrollViewwDelegate:NSObjectProtocol {
    func tappedImage(currentImage: Int)
}


class TopScrollView: UIView, UIScrollViewDelegate {
    
    var scrollView: UIScrollView = UIScrollView()
    var newsList = [PictureArticleSection]()
    var newsCount = 0
    let contextLbl = UILabel()
    let timeLbl = UILabel()
    let funLbl = UILabel()
    var timer = NSTimer()
    var delegate: MyScrollViewwDelegate?
    var currentNum: Int? = 1
    var processBarView:UIView = UIView()
    var contextView: UIView = UIView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.frame = frame
        scrollView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height/2)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.backgroundColor = UIColor.clearColor()
        scrollView.scrollsToTop = false
        scrollView.pagingEnabled = true
        scrollView.delegate = self
        self.addSubview(scrollView)
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    
    override func layoutSubviews() {

        let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapped))
        scrollView.addGestureRecognizer(tap)


        // 设置题头label
        funLbl.font = UIFont(name: "Arial Hebrew", size: CGFloat(58))
        funLbl.text = "“"
        funLbl.frame.origin = CGPoint(x: 15, y: 15)
        funLbl.frame.size = CGSize(width: 40, height: 50)
        
        
        // 设置内容label
        contextLbl.numberOfLines = 0
        contextLbl.textColor = UIColor.blackColor()
        contextLbl.font = UIFont(name: "HelveticaNeue-Light", size: CGFloat(16))
        contextLbl.frame.origin = CGPoint(x: 40, y: 20)
        // label 自动换行设置，numberOfLines需设置为0
        contextLbl.lineBreakMode = NSLineBreakMode.ByWordWrapping
        contextLbl.text = newsList[0].article
        // label自动计算高度设置，非常必要,下面的方法为可选方案
        // contextLbl.sizeToFit()
        let sizes = contextLbl.sizeThatFits(CGSize(width: bounds.width-70, height: CGFloat(MAXFLOAT)))
        contextLbl.frame.size = CGSize(width: sizes.width, height: sizes.height)
        contextLbl.autoresizesSubviews = true
        
        
        // 设置日期label
        timeLbl.textColor = UIColor.grayColor()
        timeLbl.font = UIFont(name: "HelveticaNeue-Light", size: CGFloat(14))
        timeLbl.frame.size = CGSize(width: frame.size.width, height: 20)
        timeLbl.frame.origin = CGPoint(x: 40, y: contextLbl.frame.height+25)
        timeLbl.text = dateToString(newsList[0].newsTime)
        
        //setUpSubViews()

    }
    
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        let offset = scrollView.contentOffset.x
        if offset == 0 {
            scrollView.contentOffset = CGPoint(x: CGFloat(newsList.count)*scrollView.frame.size.width, y: 0)
        } else if offset == CGFloat(newsList.count+1)*scrollView.frame.size.width {
            scrollView.contentOffset = CGPoint(x: scrollView.frame.size.width, y: 0)
        }
        let num = scrollView.contentOffset.x / scrollView.frame.size.width
        // 主线程程更新UI,麻蛋折腾了大半夜
        dispatch_async(dispatch_get_main_queue()) {
            self.currentNum = Int(num)
            if self.currentNum > self.newsList.count {
                self.currentNum = self.newsList.count
            }
            self.contextLbl.text = self.newsList[Int(num)-1].article
            self.timeLbl.text = dateToString(self.newsList[Int(num)-1].newsTime)
            // print(self.contextLbl.text)
        }

        UIView.animateWithDuration(0.3, animations: {
            self.processBarView.frame.size.width = self.frame.width/CGFloat(self.newsList.count)*num
            }, completion: { (finish:Bool)-> Void in
        })
        
    }
    
    
    func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
        let offset = scrollView.contentOffset.x
        if offset == 0 {
            scrollView.contentOffset = CGPoint(x: CGFloat(newsList.count)*scrollView.frame.size.width, y: 0)
        } else if offset == CGFloat(newsList.count+1)*scrollView.frame.size.width {
            scrollView.contentOffset = CGPoint(x: scrollView.frame.size.width, y: 0)
        }
        let num = scrollView.contentOffset.x / scrollView.frame.size.width
        dispatch_async(dispatch_get_main_queue()) {
            self.currentNum = Int(num)
            if self.currentNum > self.newsList.count {
                self.currentNum = self.newsList.count
            }
            self.contextLbl.text = self.newsList[self.currentNum!-1].article
            self.timeLbl.text = dateToString(self.newsList[self.currentNum!-1].newsTime)
            // print(self.contextLbl.text)
         }
        // print(CFRunLoopGetCurrent())
  

        UIView.animateWithDuration(0.3, animations: {
            self.processBarView.frame.size.width = self.frame.width/CGFloat(self.newsList.count)*num
            }, completion: { (finish:Bool)-> Void in
                
        })

    }
 
    func doAnimation(num: CGFloat){
        UIView.animateWithDuration(0.3, animations: {
            self.processBarView.frame.size.width = self.frame.width/CGFloat(self.newsList.count)*num
            }, completion: nil)
    }
    
    func scrollViewWillBeginDecelerating(scrollView: UIScrollView) {
        print("beginDecelerating")
    }
    
    
    func setUpSubViews() {
        
        setupImages()
        processBarView.frame = CGRect(x: 0, y: frame.size.height/2, width: self.frame.width/CGFloat(newsList.count), height: 2)
        processBarView.backgroundColor = UIColor.redColor()
        self.addSubview(processBarView)
        self.contextView = UIView(frame: CGRect(x: 0, y: frame.size.height/2+2, width: frame.size.width, height: frame.size.height/2-2))
        contextView.addSubview(funLbl)
        contextView.addSubview(contextLbl)
        contextView.addSubview(timeLbl)
        self.addSubview(contextView)
        timer = NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: #selector(self.scrollTimer), userInfo: nil, repeats: true)
    }
    
    
    func setupImages() {
        scrollView.contentSize = CGSizeMake(frame.size.width*CGFloat(newsList.count+2), 0)
        scrollView.contentOffset = CGPoint(x: frame.size.width, y: 0)
        scrollView.subviews.map(){$0.removeFromSuperview()}
        var imageRect = CGRect()
        var serailNum = Int()
        for seq in 1...newsList.count+2 {
            var recordTag = false
            if seq == 1 {
                imageRect = CGRectMake(self.frame.size.width*CGFloat(0), 0, scrollView.frame.size.width, scrollView.frame.size.height)
                serailNum = newsList.count-1
                recordTag = false
            } else if seq == newsList.count+2 {
                imageRect = CGRectMake(self.frame.size.width*CGFloat(newsList.count+1), 0, scrollView.frame.size.width, scrollView.frame.size.height)
                serailNum = 0
                recordTag = false
            } else {
                imageRect = CGRectMake(self.frame.size.width*CGFloat(seq-1), 0, scrollView.frame.size.width, scrollView.frame.size.height)
                serailNum = seq-2
                recordTag = true
            }
            
            let imageView = UIImageView(frame: imageRect)
            imageView.image = newsList[serailNum].getImage()
            if recordTag {imageView.tag=serailNum+100}
            imageView.contentMode = .ScaleAspectFill
            imageView.clipsToBounds = true
            scrollView.addSubview(imageView)
        }
    }
    
    
    func stopAnimate() {
        timer.fireDate = NSDate.distantFuture()
    }
    
    
    func startAnimate() {
        timer.fireDate = NSDate.distantPast()
    }
    
    
    func scrollTimer() {
        let offset = scrollView.contentOffset.x
        scrollView.setContentOffset(CGPoint(x: offset+scrollView.frame.size.width, y: 0), animated: true)
    }
    
    func tapped(){
        delegate?.tappedImage(currentNum!)
    }
}
